package com.example.itcacp.repository.mybatis;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.itcacp.entity.Authority;
import com.example.itcacp.entity.Role;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface RoleMapper extends BaseMapper<Role> {

    /**
     * 根据角色ID和权ID查出所有角色及对应权限
     */
    @SelectProvider(type = RoleMapper.RoleSqlProvider.class, method = "selectRoleAll")
    @Results({
            @Result(property = "roleId", column = "role_id"),
            @Result(property = "roleName", column = "role_name"),
            @Result(property = "description", column = "description"),
            @Result(property = "authorities", javaType = List.class, column = "role_id",
                    many = @Many(select = "com.example.itcacp.repository.mybatis.RoleMapper.selectAuthoritiesByRoleId"))
    })
    List<Role> selectRoleAll(String roleName, String authorityName); // 查询所有角色 结果映射

    @Select("SELECT au.* FROM it_role_authority ra " +
            "JOIN it_authority au ON ra.authority_id = au.authority_id " +
            "WHERE ra.role_id = #{roleId}")
    List<Authority> selectAuthoritiesByRoleId(Long roleId);  // 角色id查询所对应所有权限数据

    class RoleSqlProvider {
        public String selectRoleAll(String roleName, String authorityName) {
            return new org.apache.ibatis.jdbc.SQL() {{
                SELECT("r.role_id, r.role_name, r.description");
                FROM("it_role r");
                if (roleName != null && !roleName.isEmpty()) {
                    WHERE("r.role_name LIKE #{roleName}");
                }
                if (authorityName != null && !authorityName.isEmpty()) {
                    JOIN("it_role_authority ra ON r.role_id = ra.role_id");
                    JOIN("it_authority a ON ra.authority_id = a.authority_id");
                    WHERE("a.authority_name LIKE #{authorityName}");
                }
            }}.toString();
        }
    }
}



